<template>
  <div class="login-container">
    <div class="login-form">
      <div class="title-container">
        <h3 class="title"><img src="./../../assets/img/log-w.png" width="230px" alt=""></h3>
      </div>
      <div v-if="step === 1" class="formBox">
        <div class="formtablab">
          <span :class="{active: loginTypeSt == 'password'}" @click="loginType('password')">密码登录</span>
          <span :class="{active: loginTypeSt == 'phone'}" @click="loginType('phone')">验证码登录</span>
        </div>
        <el-form ref="loginForm" v-if="loginTypeSt == 'password'" :model="loginForm" :rules="loginRules" auto-complete="on" label-position="left">
          <el-form-item prop="username">
                <span class="svg-container">
                  <svg-icon icon-class="user" />
                </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="用户名"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="password">
                  <span class="svg-container">
                  <svg-icon icon-class="password" />
                </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              auto-complete="on"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                </span>
          </el-form-item>
          <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;background:linear-gradient(90deg, #7684f1, #4160e4);border:none;" @click.native.prevent="handleLogin">登录</el-button>
        </el-form>
        <el-form ref="loginFormPhone" v-if="loginTypeSt == 'phone'" :model="loginFormPhone" :rules="loginRulesPhone" auto-complete="on" label-position="left">
          <el-form-item prop="mobile">
              <span class="svg-container">
                <svg-icon icon-class="user" />
              </span>
            <el-input
              ref="mobile"
              v-model="loginFormPhone.mobile"
              placeholder="手机号"
              name="mobile"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="checkcode">
                <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
            <el-input
              ref="checkcode"
              v-model="loginFormPhone.password"
              placeholder="验证码"
              name="password"
              type="text"
              tabindex="2"
              auto-complete="on"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="getPhoneCode">{{timerText}}</span>
          </el-form-item>
          <el-button :loading="loading" type="primary" class="logBut" @click.native.prevent="handlePhoneLogin">登录</el-button>
        </el-form>
      </div>
      <div v-if="step === 2" class="formBox">
        <div class="title">请选择要进入的企业</div>
        <div class="cglist" >
          <div class="left icon"  @click="changeCompany('left')"> &#xe665; </div>
          <div class="cont" style="position: relative;flex: 1;overflow: hidden">
            <div class="cgBox" :style="posit">
                <span :class="{items:true, act: index == actId}" v-for="(item, index) in companyList" :key="index" @click="changeCompany(index)">
                  <span class="logoIcon" style="background: none;" v-if="item.logo"><img  :src="item.logo" width="100%" /></span>
                  <span class="TextIcon" v-if="!item.logo">{{item.name.substring(0, 1)}}</span>
                  <span class="logoName" v-if="index == actId">{{item.name}}</span>
                </span>
            </div>
          </div>
          <div class="right icon" @click="changeCompany('right')"> &#xe668; </div>
        </div>
        <div class="logBut but" @click="login">进入企业</div>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    name: 'Login',
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入用户名！'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (!value || value.length < 5) {
          callback(new Error('请输入密码！'))
        } else {
          callback()
        }
      }
      const validatePhone = (rule, value, callback) => {
        if (!value || !(/^1[3456789]\d{9}$/.test(value))) {
          callback(new Error('请输入正确的手机号！'))
        } else {
          callback()
        }
      }
      const validateVerification = (rule, value, callback) => {
        if (!value || value.length < 4) {
          callback(new Error('请输入验证码！'))
        } else {
          callback()
        }
      }
      return {
        loginForm: {
          username: '13111111111',
          password: '123456',
        },
        loginFormPhone: {
          mobile: '',
          password : '',
        },
        loginRules: {
          username: [{ required: true, trigger: 'blur', validator: validateUsername }],
          password: [{ required: true, trigger: 'blur', validator: validatePassword }]
        },
        loginRulesPhone: {
          mobile: [{ required: true, trigger: 'blur', validator: validatePhone }],
          checkcode: [{ required: true, trigger: 'blur', validator: validateVerification }]
        },
        loading: false,
        loginTypeSt: 'password',
        passwordType: 'password',
        redirect: undefined,
        timer: '',
        timerText: '获取验证码',
        companyId:'',
        companyList: [{name:'张三一'},{name:'里三一'},{name:'去三一'},{name:'额三一'},{name:'我三一'},{name:'姐三一'},{name:'了三一'}],
        step: 1,
        pos: 0,
        actId: 1,
        params: null,
        logoType: 'password'
      }
    },
    computed: {
      posit(){
        let left = 100 * this.pos + 'px'
        let width = 100* this.companyList.length + 'px'
        return {left,width}
      }
    },
    watch: {
      $route: {
        handler: function(route) {
          this.redirect = route.query && route.query.redirect
        },
        immediate: true
      }
    },
    methods: {
      changeCompany(st){
        if (st ==  'left' && this.actId >= 1){
          this.pos += 1
          this.actId -= 1
          this.companyId = this.companyList[this.actId].id
        }else if (st ==  'right' && this.actId <= this.companyList.length - 2){
          this.pos -= 1
          this.actId += 1
          this.companyId = this.companyList[this.actId].id
        } else if (typeof st == 'number') {
          if (st != this.actId){
            st > this.actId ? this.pos -= 1 : this.pos += 1
          }
          this.actId = st
          this.companyId = this.companyList[this.actId].id
        }
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      loginType(type){
        this.loginTypeSt = type
      },
      getPhoneCode(){
        this.$store.dispatch('user/getCodeAct', { mobile: this.loginFormPhone.mobile, type: 1} ).then((res) => {
          if (res.code == 200){
            let tim = 120
            const _this = this
            this.timerText = tim + 's'
            this.timer = setInterval(function () {
              if (tim == 1){
                clearInterval(_this.timer)
                _this.timerText = '获取验证码'
              }else{
                tim --
                _this.timerText = tim + 's'
              }
            }, 1000)
            this.loading = false
          }
        }).catch(() => {
          console.log('验证码获取失败！')
        })
      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.params = {client_id: 'pc_client', client_secret: 'pc_secret', grant_type: 'password',company_id: this.companyId,...this.loginForm}
            this.logoType = 'password'
            this.login()
          } else {
            console.log('登录失败!!')
            return false
          }
        })
      },
      handlePhoneLogin() {
        this.$refs.loginFormPhone.validate(valid => {
          if (valid) {
            this.loading = true
            this.params = {client_id: 'pc_client', client_secret: 'pc_secret', grant_type: 'password','auth_type':'sms', company_id: 3,...this.loginFormPhone}
            this.logoType = 'password'
            this.login()
          } else {
            console.log('登录失败!!')
            return false
          }
        })
      },
      login(){
        this.params.company_id = this.companyId
        const url = this.logoType == 'password' ? 'user/login': 'user/loginPhone'
        this.$store.dispatch(url, {...this.params}).then((res) => {
          if (this.step == 2) {
            this.$router.push({ path: this.redirect || '/' })
          } else {
            const id = res.data.user.userId || ''
            if (id) {
              this.getCompanyList(id)
            } else {
              this.$router.push({ path: '/' })
            }
          }
          this.loading = false
        }).catch((err) => {
          this.loading = false
        })
      },
      getCompanyList(id){
        this.$store.dispatch('user/getCompanyListAct', {id}).then(res => {
          if(res.length == 1){
            this.$router.push({ path: this.redirect || '/' })
          } else {
            this.$store.dispatch('user/logout')
            this.companyId = res[this.actId].id
            this.companyList = res
            // TODO console.log(this.companyList);
            this.step = 2
          }
        }).catch(() => {
          this.loading = false
        })
      }
    }
  }
</script>
<style>
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
  '-webkit-appearance': none;
  }
  input[type="number"]{
    appearance : none;
    -webkit-appearance: none;
    -moz-appearance: textfield;
  }
</style>
<style lang="scss">
  $bg:#283443;
  $light_gray:#fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: #333;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px #e8e8e8 inset !important;
          -webkit-text-fill-color: #333 !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg:#2d3a4b;
  $dark_gray:#889aa4;
  $light_gray:#eee;

  .login-container {
    min-height: 100%;
    min-width: 1200px;
    width: 100%;
    background:url("./../../assets/img/loginbg.png") center center no-repeat;
    background-size: cover;
    overflow: hidden;
    .formBox{
      background: #fff;
      border-radius: 5px;
      padding:20px 20px 40px 20px;
    }
    .formtablab{
      line-height: 40px;
      text-align: center;
      margin-bottom: 10px;
      span{
        display: inline-block;
        padding: 2px 15px;
        cursor: pointer;
      }
      .active{
        color: #4857ff;
        position: relative;
        &::before{
          display: inline-block;
          position: absolute;
          left: 50%;
          bottom: 5px;
          margin-left: -15px;
          content: " ";
          height: 2px;
          width: 30px;
          background: #4857ff;
        }
      }
    }
    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 250px 35px 0;
      margin: 0 auto;
      left: 350px;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 20px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
    .title{
      text-align: center;
      line-height: 44px;
      color:#666;
    }
    .cglist{
      height: 162px;
      width: 410px;
      position: relative;
      display: flex;
      padding-top: 20px;
      .left,.right {
        line-height: 100px;
        width: 50px;
        text-align: center;
        cursor: pointer;
      }
      .cgBox{
        position: absolute;
        display: flex;
        left: 0;
      }

      .items{
        display: block;
        cursor: pointer;
        position: relative;
        background: #fff;
        width: 60px;
        height: 60px;
        margin: 20px;
        line-height: 40px;
        text-align: center;
        border-radius: 100%;
        border: solid 1px #f4f4f4;
        box-shadow: 3px 3px 6px #aeaeae;
      }
      .act{
        box-shadow: 4px 4px 14px #b0b0b0;
        width: 80px !important;
        height: 80px !important;
        line-height: 60px !important;
        margin: 10px !important;
      }
    }
    .but{
      display: inline-block;
      text-align: center;
      line-height: 1;
      white-space: nowrap;
      cursor: pointer;
      background: #FFF;
      border: 1px solid #DCDFE6;
      color: #fff;
      -webkit-appearance: none;
      text-align: center;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      outline: 0;
      margin: 0;
      -webkit-transition: .1s;
      transition: .1s;
      font-weight: 500;
      padding: 12px 20px;
      font-size: 14px;
      border-radius: 4px;
    }
    .logBut{
      width:100%;
      margin-bottom:30px;
      background:linear-gradient(90deg, #7684f1, #4160e4);
      border:none;
    }
    .logoIcon{
      display: inline-block;
      width: 100%;
      height: 100%;
      border-radius: 100%;
      background: #4857ff;
      color: #fff;
      font-size: 32px;
      img{
        width: 60px;
        height: 60px;
        border-radius: 100%;
      }
    }
    .act{
      img{
        width: 80px;
        height: 80px;
      }
    }
    .logoName{
      position: absolute;
      bottom: -30px;
      left: 0;
      color: #4857ff;
      width: 80px;
      height: 40px;
      overflow: hidden;
      font-size: 14px;
      text-align: center;
      &::before{
        content: ' ';
        width: 0;
        height: 0;
        position: absolute;
        left: 35px;
        top: 10px;
        border: 5px solid;
        border-color: transparent transparent #4857ff transparent;
      }
    }
    .TextIcon{
      display: inline-block;
      width: 100%;
      height: 100%;
      border-radius: 100%;
      background: #4857ff;
      color: #fff;
      font-size: 32px;
      padding: 10px;
    }
  }
</style>
